<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRole"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" border="">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="scope">
                  <!-- slot-scope插槽看表单组件 -->
                  <!-- {{ scope.row.id }} -->
                  <el-button size="small" type="success" @click="assignPerm(scope.row.id)">分配权限</el-button>
                  <!-- 这里的row是element的表格规定的行数据 -->
                  <el-button size="small" type="primary" @click="editRole(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page.page"
                :page-size="page.pagesize"
                :total="page.total"
                layout="prev,pager,next"
                @current-change="changePage"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input v-model="company.name" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="company.companyAddress" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="company.mailbox" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="company.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增及编辑的弹出框 -->
      <el-dialog :title="roleForm.id?'编辑':'新增'" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹窗 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- show-checkbox 显示多选框 -->
        <!-- check-strictly 父子之间不关联，这个必须加哦 -->
        <!-- 这个组件没有v-model， 所以如果想要设置选中值，需要两个配合-->
        <!-- 分别是setCheckedKeys跟node-key属性 -->
        <!-- node-key告诉树形组件每个权限对象的那个属性是唯一标识 （id） -->
        <el-tree
          ref="premTree"
          :data="permList"
          :props="{label: 'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { deleteRole, getCompanyById, addRole, getRoleDetailById, updateRoleById } from '@/api/settings'
import { getRoleList, assignPerm } from '@/api/settings'
import { listToTreeData } from '@/utils'
import { getPermList } from '@/api/permission'
export default {
  data() {
    return {
      company: {},
      list: [],
      page: {
        page: 1,
        pagesize: 5,
        total: 0 // 记录总数
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      // 展示权限弹窗
      showPermDialog: false,
      // 权限
      permList: [],
      userId: ''
    }
  },
  created() {
    this.getCompanyById()
    // 调用所有角色列表
    this.getRoleList()
    // 调用获取所有的权限
    this.getPermList()
  },
  methods: {
    async getCompanyById() {
      this.company = await getCompanyById()
    },
    // 角色
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      // console.log(total, rows)
      this.list = rows
      this.page.total = total
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getRoleList()
    },
    // 删除角色
    async deleteRole(id) {
      await this.$confirm('确认删除改角色吗')
      await deleteRole(id)
      this.$message.success('删除角色成功')
      // this.page.page = Math.floor(this.page.total / this.page.pagesize)
      // 更新页面
      // 当页面只有一条数据且当前页码的索引大于1时，才调用获取列表
      if (this.list.length === 1 && this.page.page > 1) {
        // console.log(1)
        this.page.page--
      }
      this.getRoleList()
    },
    // 新增弹出框
    addRole() {
      this.showDialog = true
    },
    // 编辑弹出框
    async editRole(id) {
      // 回填数据
      this.roleForm = await getRoleDetailById(id)
      this.showDialog = true
    },
    // 点击确定新增或者编辑
    async btnOK() {
      // 1、校验
      await this.$refs.roleForm.validate()
      // 2、请求
      if (this.roleForm.id) {
        // 编辑
        await updateRoleById(this.roleForm)
      } else {
        // 新增
        await addRole(this.roleForm)
        // 新增当前总条数+1
        this.page.total++
        const pageSize = this.page.pagesize
        // 拿到新的总条数/页容量 向上取整得到页码
        this.page.page = Math.ceil(this.page.total / pageSize)
      }
      // 3、弹出提示
      this.$message.success('操作成功')
      // 4、更新
      this.getRoleList()
      // 5、关闭弹框
      this.showDialog = false
    },
    async btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      await this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 获取权限名称
    async getPermList() {
      this.permList = listToTreeData(await getPermList(), '0')
      console.log(this.permList)
    },
    async assignPerm(id) {
      console.log(id)
      const { permIds } = await getRoleDetailById(id)
      console.log(permIds)
      this.userId = id
      this.showPermDialog = true
      // this.$nextTick(() => {
      // 回填权限 等到渲染完再显示，DOM数据渲染是异步的。
      setTimeout(() => {
        this.$refs.premTree.setCheckedKeys(permIds)
      }, 100)
      // })
    },
    async btnPermOK() {
      // 发请求
      await assignPerm({
        id: this.userId,
        permIds: this.$refs.premTree.getCheckedKeys()
      })
      this.$message.success('修改成功')
      // 弹窗消失
      this.showPermDialog = false
    },
    btnPermCancel() {
      this.showPermDialog = false
    }

  }
}
</script>

<style>
</style>
